package hufs.cskim.media;

import java.util.ArrayList;

import android.app.Activity;
import android.content.Intent;
import android.database.Cursor;
import android.database.sqlite.SQLiteDatabase;
import android.os.Bundle;
import android.view.View;
import android.widget.AdapterView;
import android.widget.AdapterView.OnItemClickListener;
import android.widget.ListView;

public class PlayList extends Activity implements OnItemClickListener {

	private DatabaseHelper helper;
	private ArrayList<MusicInfo> list;
	private PlayListAdapter adapter;
	
	private ListView listView;
	
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		// TODO Auto-generated method stub
		super.onCreate(savedInstanceState);
		setContentView(R.layout.list);
		
		listView = (ListView)findViewById(R.id.list);
		list = new ArrayList<MusicInfo>();
		
		listup();
		
		adapter = new PlayListAdapter(this, R.layout.list_row, list);
		listView.setAdapter(adapter);
		listView.setOnItemClickListener(this);
	}

	private void listup() {
		// TODO Auto-generated method stub
		helper = new DatabaseHelper(this);
		SQLiteDatabase db = helper.getReadableDatabase();
		Cursor cursor;
		MusicInfo info = null;
		
		String title, artist, img, uri;
		int titleIndex, artistIndex, imgIndex, uriIndex;
		
		cursor = db.rawQuery("SELECT * FROM list", null);
		
		if(cursor.moveToFirst()){
			do {
				titleIndex = cursor.getColumnIndex("title");
				artistIndex = cursor.getColumnIndex("artist");
				imgIndex = cursor.getColumnIndex("img");
				uriIndex = cursor.getColumnIndex("uri");
				
				title = cursor.getString(titleIndex);
				artist = cursor.getString(artistIndex);
				img = cursor.getString(imgIndex);
				uri = cursor.getString(uriIndex);
				
				info = new MusicInfo(title, artist, img, uri);
				
				list.add(info);
			}while(cursor.moveToNext());
		}
		
		db.close();
		helper.close();
	}

	@Override
	public void onItemClick(AdapterView<?> arg0, View arg1, int arg2, long arg3) {
		// TODO Auto-generated method stub
		
		Bundle extra;
		Intent intent;
		 
		extra = new Bundle();
		intent = new Intent();

		extra.putSerializable("music", list.get(arg2));
		intent.putExtras(extra);
		
		this.setResult(Activity.RESULT_OK, intent);
		this.finish();
	}
}
